package com.wzdigit.wms.raw.service.backtosap;

import com.alibaba.fastjson.JSON;
import com.wzdigit.framework.Shift;
import com.wzdigit.wms.basic.domain.basic.Sku;
import com.wzdigit.wms.basic.domain.basic.Warehouse;
import com.wzdigit.wms.basic.domain.mapping.CodeMapping;
import com.wzdigit.wms.basic.mapper.core.basic.SkuMapper;
import com.wzdigit.wms.basic.mapper.core.basic.WarehouseMapper;
import com.wzdigit.wms.basic.mapper.core.mapping.CodeMappingMapper;
import com.wzdigit.wms.basic.service.code.CodeMappingService;
import com.wzdigit.wms.common.entity.StatusCode;
import com.wzdigit.wms.common.utils.SapWebServiceUtil;
import com.wzdigit.wms.raw.domain.dto.SapStoreDto;
import com.wzdigit.wms.raw.exception.SystemException;
import com.wzdigit.wms.web.service.common.wms2sap.ZDT_MsgHeader;
import com.wzdigit.wms.web.service.wms2sap.getstore.*;
import com.wzdigit.wms.web.service.wms2sap.waitcheckinstore.ZDT_064_ReqRECORDS;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

/*
    * 库存获取接口
    * @author shuaic
    * @date 2021/6/18 16:56
*/
@Service
@Slf4j
public class GetStoreBackService {

    @Autowired
    private CodeMappingService codeMappingService;

    @Autowired
    SkuMapper skuMapper ;

    @Autowired
    CodeMappingMapper codeMappingMapper ;

    @Autowired
    WarehouseMapper warehouseMapper ;

    @Value("${sap.web.service.protocol-head}")
    private String protocolHead;

    @Value("${sap.web.service.getStore-url}")
    private String uri;

    @Value("${wzdigit.web.service.sap.ip}")
    private String ip;

    /*
        * @param factory 工厂代码
    	* @param skuId  物料ID
    	* @param whsId  仓库ID
        * @return void
        * @author shuaic
        * @date 2021/6/18 17:02
    */
    public List<SapStoreDto>  getStoreFromSap(String factory,String skuCode,Integer whsId,Integer status){

        //查询仓库
        Warehouse warehouse = warehouseMapper.selectById(whsId);
        CodeMapping codeMapping = codeMappingService.selectByWhsCodeAndFactoryOrQaStatus(factory, warehouse.getWhsCode(), status);
        List<ZDT_070_ReqRECORDS> list = new ArrayList<>();
        ZDT_070_ReqRECORDS records = new ZDT_070_ReqRECORDS();
        records.setWERKS(factory);
        records.setMATNR(skuCode);
        records.setLGORT(codeMapping.getMappingCode());
        list.add(records);
        List<SapStoreDto> report = report(list);
        return report;
    }


    public List<SapStoreDto> report(List<ZDT_070_ReqRECORDS> records) {
        log.info("开始调【SAP库存获取接口】");
        //发送【向SAP报检】的路径
        String urlString = protocolHead + ip + uri;

        log.info("发送报文的路径:" + urlString);

        ZSI_070_WMS2SAP_OutProxy proxy = new ZSI_070_WMS2SAP_OutProxy  ();

        proxy.setEndpoint(urlString);

        log.info("ZSI_070_WMS2SAP_OutProxy:" + proxy.toString());

        // 消息头
        ZDT_MsgHeader header = SapWebServiceUtil.getHeader();

        log.info("header:" + header);


        //输出请求的核心报文
        try {
            for (ZDT_070_ReqRECORDS record : records) {

                //格式化生成的XML报文
                JAXBContext jc = JAXBContext.newInstance(ZDT_070_ReqRECORDS.class);
                Marshaller ms = jc.createMarshaller();
                ms.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                Writer writer = new StringWriter();
                ms.marshal(record, writer);

                log.info("发送报文的核心内容【xml】:" + writer.toString());
            }
        } catch (JAXBException e) {
            e.printStackTrace();
            log.error("转成XML出错");
        }


        ZDT_070_Req req = new ZDT_070_Req();

        // 消息头
        req.setHEADER(header);
        // 记录
        ZDT_070_ReqRECORDS [] reqRECORDS = records.toArray(new ZDT_070_ReqRECORDS [records.size()]);
        req.setRECORDS(reqRECORDS);

        ZDT_070_Rsp rsp = null;


        try {
            //调接口
            rsp = proxy.ZSI_070_WMS2SAP_Out(req);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        log.info("SAP库存接口完成，输出的报文为==》"+JSON.toJSONString(rsp));
        if(rsp.getHEADER()==null){
            Shift.fatal("获取SAP库存失败，SAP库存获取接口未返回任何信息！");
        }
        if("E".equals(rsp.getHEADER().getSTATUS())){
            Shift.fatal("获取SAP库存失败，SAP返回的错误信息为:【"+rsp.getHEADER().getMESSAGE()+"】");
        }
        List<SapStoreDto> list = new ArrayList<>();


        ZDT_070_RspRECORDS[] rspArr = rsp.getRECORDS();
        for(ZDT_070_RspRECORDS item : rspArr){
            SapStoreDto dto = new SapStoreDto();
            dto.setFactory(item.getWERKS());
            dto.setHoldQty(item.getSPEME());
            dto.setOnWayQty(item.getUMLME());
            dto.setPlace(item.getLGORT());
            dto.setPlaceDesc(item.getLGOBE());
            dto.setQty(item.getLABST());
            dto.setQuantityQty(item.getINSME());
            dto.setSaleQty(item.getKALAB());
            dto.setSkuCode(item.getMATNR());
            dto.setUnit(item.getMEINS());
            list.add(dto);
        }

        //输出请求的核心报文
      /*  try {
            for (ZDT_070_RspRECORDS rspRecordHead : rspArr) {

                //格式化生成的XML报文
                JAXBContext jc = JAXBContext.newInstance(ZDT_070_RspRECORDS.class);
                Marshaller ms = jc.createMarshaller();
                ms.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                Writer writer = new StringWriter();
                ms.marshal(rspRecordHead, writer);

                log.info("【SAP_库存获取接口】返回报文的核心内容【xml】:" + writer.toString());
            }
        } catch (JAXBException e) {
            e.printStackTrace();
            log.error("转成XML出错");
        }*/

        return list;
    }
}
